'''
Created on 2020年3月3日
服务项目管理
@author: Administrator
'''
import datetime

from dateutil.relativedelta import relativedelta

from common.public import *
from orm.model import TransForm, Document, TransFormDetail, WorkOrder, AgentKeeping, AgentKeepingDetails, db
import pandas as pd
from view.baseview import BaseView


class TransFormDetailView(BaseView):
    def __init__(self):
        pass

    def query(self, params):
        """根据条件取得服务列表，params：条件参数"""
        result=[]
        rows = TransFormDetail.select().where(TransFormDetail.transform == params["id"]).order_by(TransFormDetail.id)
        for row in rows:
            data = {
                "id":row.id,
                "name":row.name,
                "time":row.time,
                "unit":row.unit,
                "cost":row.cost,
                "price":row.price,
                "memo":row.memo
             }
            result.append(data )
        return super().resultSet(200, "", result)

    @db.atomic()                   
    def updatestatus(self, params):
        """
        更新分配状态
        """
        print(params[0]["transformid"])
        transform = TransForm.get(TransForm.id == params[0]["transformid"])
        transform.status = "已分配"
        transform.save()
        return super().resultSet(200, "分配成功", [])
        raise Exception("添加失败")    

    @db.atomic()                   
    def createdocument(self, params):
        """
        更新分配状态
        """
        data_document = []
        print(params[0]["customerid"])
        document, created = Document.get_or_create(customer_id = params[0]["customerid"] , defaults = {'customer_id': params[0]["customerid"]})
        document.save()
        data_document.append(document.id)
        return super().resultSet(200, "分配成功", data_document)
        raise Exception("添加失败")  
    @db.atomic()                   
    def assignment(self, params, documentId):
        """
        添加工单服务
        """
        print(params)
        transform = TransForm.get(TransForm.id == params["transformid"])
        # for item in params:
        WorkOrder.create(
            transform_id = params["transformid"],
            leader_id = params["leader"],
            servicedetail_id = params["servicedetailid"],
            customer_id = params["customerid"],
            name = params["name"],
            document_id = documentId,
            remake = transform.memo,
            enddate = params["enddate"],
            update_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
            create_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            )
        # data.append(super().resultSet(200, "分配成功", []))
        return super().resultSet(200, "分配成功", [])
        raise Exception("添加失败") 

    @db.atomic()                   
    def aggentkeeping(self, params, documentId):
        """
        添加代理记账服务
        """
        print(params)
        transform = TransForm.get(TransForm.id == params["transformid"])
        agentkeeping = AgentKeeping.create(
            transform_id = params["transformid"],
            transform_detail_id = params["id"],
            leader_id = params["leader"],
            amount = params["amount"],
            unit = params["unit"],
            servicedetail_id = params["servicedetailid"],
            customer_id = params["customerid"],
            name = params["name"],
            document_id = documentId,
            remake = transform.memo,
            enddate = params["enddate"],
            update_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
            create_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            )
        enddate = params["enddate"][0:10]
        new_time = datetime.datetime.strptime(enddate, '%Y-%m-%d')
        months = 0
        if params["unit"] == "年":
            months = params["amount"] * 12
        elif params["unit"] == "月":
            months = params["amount"] * 1
        month_ago = new_time - relativedelta(months = months)
        new_timestr = new_time.strftime('%Y%m%d')
        month_agostr = month_ago.strftime('%Y%m%d')
        year_month_list = pd.date_range(start = month_agostr, end = new_timestr, freq = 'M').tolist()
        
        data_year_months = year_month_list
        
        # 需要的时间列表
        data_year_months_conditions = []
        for data_year_month in data_year_months:
            
            data_year_month = data_year_month.strftime("%Y-%m")
            
            if data_year_month[5:7] in ['01', '04', '07', '10']:
                data_year_months_conditions.append(data_year_month)
        items = CONTENT_OF_KEEPINGING_AGENT
        itemconditions = COPY_TAX_NATIONAL_TAX_SMALL_SCALE_QUARTER
        result = []
        for month in data_year_months:
            month = month.strftime("%Y-%m")
            for item in items:
                data = {
                    "keepaccount_id": agentkeeping.id,
                    "charger_id": params["leader"],
                    "matter": item,
                    "status":'未完成',
                    "month":month,
                    "remake": '无',
                    "evidence": '[]',
                    "update_time": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
                    "create_time": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
                    }
                if month in data_year_months_conditions:
                    data = data
                else:
                    if item in itemconditions:
                        data = {
                            "keepaccount_id": agentkeeping.id,
                            "charger_id": params["leader"],
                            "matter": item,
                            "status":'',
                            "month":month,
                            "remake": '无',
                            "evidence": '[]',
                            "update_time": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
                            "create_time": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
                        }
                result.append(data)
        print(result)

        AgentKeepingDetails.insert_many(result).execute()

        return super().resultSet(200, "分配成功", [])
        raise Exception("添加失败")           
    @db.atomic()                   
    def add(self, params):
        """
        添加服务项目
        """
        TransFormDetail.create(
                transform = params["transformid"],
                    name = params["name"],
                    time = params["time"],
                    unit = params["unit"],
                    cost = params["cost"],
                    price = params["price"],
                    memo = params["memo"]
                    )
        return super().resultSet(200, "添加成功", [])
        raise Exception("添加失败")         
    
    @db.atomic()                   
    def update(self, params):
        """
        更新服务项目
        """
        rec= TransFormDetail.get(TransFormDetail.id==params["id"])
        rec.name=params["name"]
        rec.time=params["time"]
        rec.unit=params["unit"]
        rec.cost=params["cost"]
        rec.price=params["price"]
        rec.memo=params["memo"]
        rec.save()
        return super().resultSet(200, "更新成功", [])
        raise Exception("更新失败")
    
    @db.atomic()                   
    def delete(self, params):
        """
        删除服务项目
        """
        TransFormDetail.delete().where(TransFormDetail.id==params["id"]).execute()
        return super().resultSet(200, "删除成功", {})
        raise Exception("删除失败")
    
